import { fileURLToPath, URL } from 'node:url'
import { cwd } from 'node:process'

import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import AutoImport from 'unplugin-auto-import/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import Components from 'unplugin-vue-components/vite'

// https://vitejs.dev/config/
export default defineConfig(({ command, mode }) => {
  const isBuild = command === 'build'
  const env = loadEnv(mode, cwd())
  return {
    base: '/admin/',
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url))
      }
    },
    server: {
      host: '0.0.0.0',
      port: 5165,
      strictPort: true,
      proxy: {
        [env.VITE_API_PATH]: {
          target: env.VITE_ORIGIN,
          changeOrigin: true,
          rewrite: path => path.replace(/^\/api/, '')
        }
      },
      open: '/admin/login'
    },
    build: {
      outDir: 'admin',
      sourcemap: !isBuild,
      chunkSizeWarningLimit: 1000,
      minify: 'esbuild'
    },
    plugins: [
      AutoImport({
        imports: [
          'vue',
          'vue-router',
          {
            'element-plus': [
              // named imports
              'ElMessage', // import { ElMessage } from 'element-plus',
              'ElMessageBox'
            ]
          }
        ],
        dts: 'src/types/auto-imports.d.ts',
        resolvers: [ElementPlusResolver()]
      }),
      Components({
        dts: 'src/types/components.d.ts',
        resolvers: [ElementPlusResolver()]
      }),

      vue({
        template: {
          compilerOptions: {
            isCustomElement: tag => tag.startsWith('media-')
          }
        }
      })
    ]
  }
})
